package com.example.tongyao.system.config;

import com.example.tongyao.system.entity.SysUser;
import com.example.tongyao.utils.token.TokenUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * TongYao2.0 >>> 【com.example.tongyao.system.config】
 * Security 验证登录和证书颁发
 *
 * @author: tongyao
 * @since: 2021-08-01 11:14
 */
@Component
public class SecurityAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private UserDetailsService userDetailService;

    @Resource
    private TokenUtil tokenUtil;

    /**
     * 账号密码处理，和  jwt      token证书颁发
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        // 这个获取表单输入中返回的用户名;
        String userName = authentication.getName();

        // 这个是表单中输入的密码；
        String password = (String) authentication.getCredentials();

        // 这里构建来判断用户是否存在和密码是否正确      // 这里调用我们的自己写的获取用户的方法；
        SysUser userInfo = (SysUser) userDetailService.loadUserByUsername(userName);
        if (userInfo == null) {
            throw new BadCredentialsException("用户名不存");
        }else if (!userInfo.isEnabled()) {
            throw new DisabledException("用户已被禁用");
        } else if (!userInfo.isAccountNonExpired()) {
            throw new AccountExpiredException("账号已过期");
        } else if (!userInfo.isAccountNonLocked()) {
            throw new LockedException("账号已被锁定");
        } else if (!userInfo.isCredentialsNonExpired()) {
            throw new LockedException("凭证已过期");
        }else if(userInfo.getRoleId() == null || userInfo.getRoleId().equals("")){
            throw new BadCredentialsException("登录失败！该用户未设置角色权限！");
        }

        //加解密，密码校验
        if (!userInfo.getPassword().equals(password)) {
            throw new BadCredentialsException("密码不正确");
        }

        Collection<? extends GrantedAuthority> authorities = userInfo.getAuthorities();

        //创建jwt   token
        String token = tokenUtil.createToken(userInfo);
        userInfo.setAccess_token(token);

        // 构建返回的用户登录成功的token
        return new UsernamePasswordAuthenticationToken(userInfo, password, authorities);
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}